import 'package:flutter/material.dart';
import '../../models/comment_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 评论页面
class CommentPage extends StatefulWidget {
  final String postId;
  final String postTitle;
  final int initialCommentsCount;

  const CommentPage({
    super.key,
    required this.postId,
    required this.postTitle,
    required this.initialCommentsCount,
  });

  @override
  State<CommentPage> createState() => _CommentPageState();
}

class _CommentPageState extends State<CommentPage> {
  final TextEditingController _commentController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final ApiService _apiService = ApiService();
  
  List<CommentModel> _comments = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  final int _pageSize = 20;
  int _commentsCount = 0;

  @override
  void initState() {
    super.initState();
    _commentsCount = widget.initialCommentsCount;
    _scrollController.addListener(_onScroll);
    _loadComments();
  }

  @override
  void dispose() {
    _commentController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 滚动监听，实现上拉加载更多
  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 200) {
      if (!_isLoading && _hasMore) {
        _loadMoreComments();
      }
    }
  }

  /// 加载评论列表
  Future<void> _loadComments({bool refresh = false}) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      if (refresh) {
        _currentPage = 1;
        _hasMore = true;
        _comments.clear();
      }
    });

    try {
      final result = await _apiService.getPostComments(
        widget.postId,
        page: _currentPage,
        size: _pageSize,
      );

      final List<dynamic> commentsData = result['list'] ?? [];
      final List<CommentModel> newComments = commentsData
          .map((commentJson) => CommentModel.fromJson(commentJson))
          .toList();

      setState(() {
        if (refresh) {
          _comments = newComments;
          _currentPage = 2; // 重置为第二页
        } else {
          _comments.addAll(newComments);
          _currentPage++;
        }
        _hasMore = newComments.length >= _pageSize;
        _commentsCount = result['total'] ?? _comments.length;
      });

      Logger.d('CommentPage', '加载评论成功，当前数量: ${_comments.length}');
    } catch (e) {
      Logger.e('CommentPage', '加载评论失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('加载评论失败: ${e is NetworkException ? e.message : '网络错误'}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 加载更多评论
  Future<void> _loadMoreComments() async {
    await _loadComments();
  }

  /// 刷新评论
  Future<void> _refreshComments() async {
    await _loadComments(refresh: true);
  }

  /// 添加评论
  Future<void> _addComment() async {
    final content = _commentController.text.trim();
    if (content.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入评论内容')),
      );
      return;
    }

    try {
      setState(() => _isLoading = true);
      
      await _apiService.addComment(widget.postId, content);
      
      _commentController.clear();
      setState(() {
        _commentsCount++;
      });
      
      // 刷新评论列表
      await _refreshComments();
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('评论成功'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      Logger.e('CommentPage', '添加评论失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('评论失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  /// 点赞/取消点赞评论
  Future<void> _likeComment(CommentModel comment) async {
    try {
      // 先更新UI
      setState(() {
        final index = _comments.indexWhere((c) => c.id == comment.id);
        if (index != -1) {
          final newLikesCount = comment.isLiked ? comment.likesCount - 1 : comment.likesCount + 1;
          _comments[index] = comment.copyWith(
            isLiked: !comment.isLiked,
            likesCount: newLikesCount,
          );
        }
      });

      // 调用API
      await _apiService.likeComment(comment.id, !comment.isLiked);
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!comment.isLiked ? '已点赞' : '已取消点赞'),
          duration: const Duration(seconds: 1),
        ),
      );
    } catch (e) {
      Logger.e('CommentPage', '点赞操作失败: $e');
      // 回滚UI状态
      setState(() {
        final index = _comments.indexWhere((c) => c.id == comment.id);
        if (index != -1) {
          _comments[index] = comment;
        }
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('评论 ($_commentsCount)'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 1,
      ),
      body: Column(
        children: [
          // 评论输入区域
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(color: Colors.grey.withOpacity(0.1)),
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _commentController,
                    decoration: const InputDecoration(
                      hintText: '写下你的评论...',
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _addComment(),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _isLoading ? null : _addComment,
                  child: const Text('发送'),
                ),
              ],
            ),
          ),
          
          // 评论列表
          Expanded(
            child: RefreshIndicator(
              onRefresh: _refreshComments,
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(16),
                itemCount: _comments.length + (_isLoading ? 1 : 0),
                itemBuilder: (context, index) {
                  if (index == _comments.length) {
                    return _buildLoadingIndicator();
                  }
                  final comment = _comments[index];
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 16),
                    child: _buildCommentCard(comment),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建评论卡片
  Widget _buildCommentCard(CommentModel comment) {
    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Row(
              children: [
                CircleAvatar(
                  radius: 16,
                  backgroundImage: comment.userAvatar != null && comment.userAvatar!.isNotEmpty
                      ? NetworkImage(comment.userAvatar!)
                      : null,
                  child: comment.userAvatar == null || comment.userAvatar!.isEmpty
                      ? const Icon(Icons.person, size: 16)
                      : null,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        comment.username,
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                        ),
                      ),
                      Text(
                        comment.timeAgo,
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 评论内容
            Text(
              comment.content,
              style: const TextStyle(fontSize: 14),
            ),
            const SizedBox(height: 8),
            
            // 操作按钮
            Row(
              children: [
                GestureDetector(
                  onTap: () => _likeComment(comment),
                  child: Row(
                    children: [
                      Icon(
                        comment.isLiked ? Icons.favorite : Icons.favorite_border,
                        size: 16,
                        color: comment.isLiked ? Colors.red : Colors.grey[600],
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '${comment.likesCount}',
                        style: TextStyle(
                          color: comment.isLiked ? Colors.red : Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 16),
                GestureDetector(
                  onTap: () {
                    // TODO: 实现回复功能
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('回复功能待开发')),
                    );
                  },
                  child: Row(
                    children: [
                      Icon(Icons.reply, size: 16, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '回复',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建加载指示器
  Widget _buildLoadingIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: _isLoading
          ? const CircularProgressIndicator()
          : _hasMore
              ? const SizedBox.shrink()
              : const Text(
                  '没有更多评论了',
                  style: TextStyle(color: Colors.grey),
                ),
    );
  }
}
